package com.kidback.bbloc259.ui.map;


import android.graphics.BitmapFactory;
import android.graphics.Color;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.kidback.bbloc259.R;
import com.kidback.bbloc259.api.BBNetApi;
import com.kidback.bbloc259.app.provider.DeviceDataProvider;
import com.kidback.bbloc259.app.provider.UserDataProvider;
import com.kidback.bbloc259.bean.DeviceBean;
import com.kidback.bbloc259.event.UserLocEvent;
import com.kidback.bbloc259.network.base.ApiHelper;
import com.kidback.bbloc259.network.beans.BaseResponse;
import com.kidback.bbloc259.network.errorhandler.ResponseThrowable;
import com.kidback.bbloc259.network.observer.BaseObserver;
import com.kidback.bbloc259.util.CollectionUtils;
import com.kidback.bbloc259.util.LogUtils;
import com.kidback.bbloc259.util.StringUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class UserMapLayer {

    private MapFragment mapFragment;
    private MapView mapView;

    private List<LatLng> latLngList = new ArrayList<>();
    private Polyline polyline;
    private Marker marker;

    public UserMapLayer(MapFragment mapFragment, MapView mapView) {
        this.mapFragment = mapFragment;
        this.mapView = mapView;
    }

    public void init() {
        if (DeviceDataProvider.getInst().get() != null &&
                DeviceDataProvider.getInst().get().lastLocation != null) {
            AMapLocation aMapLocation = DeviceDataProvider.getInst().get().lastLocation;
            refreshMyLoc(aMapLocation);


            LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            /**
             * CameraPosition 第一个参数： 目标位置的屏幕中心点经纬度坐标。
             * CameraPosition 第二个参数： 目标可视区域的缩放级别
             * CameraPosition 第三个参数： 目标可视区域的倾斜度，以角度为单位。
             * CameraPosition 第四个参数： 可视区域指向的方向，以角度为单位，从正北向顺时针方向计算，从0度到360度
             */
            CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 14, 0, 0));
            mapView.getMap().animateCamera(cameraUpdate);
        }

//        mapView.getMap().setCustomMapStyle(
//                new com.amap.api.maps.model.CustomMapStyleOptions()
//                        .setEnable(true)
//                        .setStyleDataPath("/mnt/sdcard/amap/style.data")
//                        .setStyleExtraPath("/mnt/sdcard/amap/style_extra.data"));
    }

    private void refreshMyLoc(AMapLocation aMapLocation) {
        //绘制最新位置
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()));
        markerOption.title("我的位置").snippet("我的位置");
        markerOption.draggable(false);
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(mapFragment.getResources(), R.mipmap.avatar_default)));
        markerOption.setFlat(true);
        if (marker != null) {
            marker.remove();
        }
        marker = mapView.getMap().addMarker(markerOption);
    }

    public void addMyPoint(AMapLocation aMapLocation) {

        //过滤无效数据
        if (aMapLocation.getLatitude() == 0f || aMapLocation.getLongitude() == 0f) {
            return;
        }

        //保存设备最后一次定位
        if (DeviceDataProvider.getInst().get() == null) {
            DeviceDataProvider.getInst().put(new DeviceBean());
        }
        DeviceDataProvider.getInst().get().lastLocation = aMapLocation;
        DeviceDataProvider.getInst().save();


        refreshMyLoc(aMapLocation);


        //绘制轨迹
        LatLng latLngNow = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
        if (CollectionUtils.size(latLngList) > 1) {
            float distance = AMapUtils.calculateLineDistance(CollectionUtils.last(latLngList), latLngNow);
            if (distance < 50) {
                LogUtils.e(StringUtils.format("距离上一次有效定位点为 %.2f 米", distance));
                return;
            }
        }

        UserLocEvent event = new UserLocEvent();
        event.aMapLocation = aMapLocation;
        EventBus.getDefault().post(event);


//        latLngList.add(new LatLng(aMapLocation.getLatitude() * (0.98 + Math.random() * 4 / 100f),
//                aMapLocation.getLongitude() * (0.99 + Math.random() * 2 / 100f)));

        latLngList.add(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()));

        if (CollectionUtils.size(latLngList) > 100) {
            latLngList.remove(0);
        }

        if (CollectionUtils.size(latLngList) >= 2) {
            if (polyline != null) {
                polyline.remove();
            }
            polyline = mapView.getMap().addPolyline(new PolylineOptions().
                    addAll(latLngList).width(10).color(Color.argb(255, 255, 1, 1)));
        }

        reportLocation(aMapLocation);

    }

    private void reportLocation(AMapLocation aMapLocation) {

        String userId = UserDataProvider.getInst().getUserId();
        double latitude = aMapLocation.getLatitude();
        double longitude = aMapLocation.getLongitude();
        String address = aMapLocation.getAddress();


        //userId = "16020017CD5FF40C6849F18B5BADB0A9";


        Observable<BaseResponse<Void>> observable = BBNetApi.getBBService().locationReport(userId, latitude, longitude, address);
        Observer<BaseResponse<Void>> observer = new BaseObserver<BaseResponse<Void>>() {

            @Override
            public void onSubscribe(Disposable d) {
                super.onSubscribe(d);
            }

            @Override
            public void onSuccess(BaseResponse<Void> orderResponse) {
                LogUtils.e("上报用户定位点成功");
            }

            @Override
            public void onFailure(ResponseThrowable e) {
                LogUtils.e("上报用户定位点失败");
            }
        };

        ApiHelper.request(observable, observer);

    }

}
